package com.example.comitclx1.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.comitclx1.mapper.OperateLogMapper;
import com.example.comitclx1.pojo.OperateLog;
import com.example.comitclx1.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.example.comitclx1.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //操作人id-当前员工id
        String jwt = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
       Integer operateUser=(Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime=LocalDateTime.now();
        //操作类名
        String className=joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        String methodParams = (String) Arrays.toString(joinPoint.getArgs());
        //调用原始目标方法运行
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        //方法返回值
        String returnValue= JSONObject.toJSONString(result);
        //操作耗时
        long costTime = end-begin;

        //记入操作日志
        OperateLog operateLog=new OperateLog(null,operateUser,operateTime,className,methodName,
                methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);
        return result;
    }
}
